/*
 * Copyright (C) 2009 AnK Team
 *	 Andrey Korolev
 *	 Anna Krel
 *	 Anna Kapanina
 *	 
 *	 http://code.google.com/p/ankfood/	
 *    
     
 *    Licensed under the GNU General Public License, Version 2.0 (the "License");
 *
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *         http://www.gnu.org/licenses/gpl-2.0.html

 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,

 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */



package org.ank.food;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ViewProfileActivity extends Activity{
	
	private boolean back;
	
	public static final int CALLER_PROFILE_CHOOSE = 0;
	public static final int CALLER_EATEN_TODAY = 1;
	public static final String INTENT_EXTRA_NAME = "caller";
	public static final String PREFS_PROFILE_NAME = "name";
	public static final String PREFS_PROFILE_AGE = "age";
	public static final String PREFS_PROFILE_GENDER = "gender";
	public static final String PREFS_PROFILE_WEIGHT = "weight";
	public static final String PREFS_PROFILE_HEIGHT = "height";
	public static final String PREFS_PROFILE_PHYSACT = "physact";
	public static final String PREFS_WEIGHT_UNIT = "weight unit";
	public static final String PREFS_HEIGHT_UNIT = "height unit";
	public static final int METRIC = 0;
	public static final int ENGLISH = 1;
	
	
	private Button cancelButton,saveButton;
	private TextView title;
	private EditText nameEditText,ageEditText,weightEditText,heightEditText;
	private RadioGroup weightGroup,heightGroup,genderGroup;
//	private ProfileManager ProfileManager.getInstance(getApplicationContext());
	private int caller;
	private Spinner physActSpinner;

	
	@Override
	public void onCreate(Bundle b){
		
		super.onCreate(b);
//		Log.v("Act","onCreate");
		setContentView(R.layout.view_profile_activity);
		back = false;
		
		Intent parentIntent = getIntent();
		caller = parentIntent.getIntExtra(INTENT_EXTRA_NAME, CALLER_PROFILE_CHOOSE);		
		
		saveButton = (Button)findViewById(R.id.view_profile_save_button);
		cancelButton = (Button)findViewById(R.id.view_profile_cancel_button);
		nameEditText = (EditText)findViewById(R.id.view_profile_name_edittext);
		ageEditText = (EditText)findViewById(R.id.view_profile_age_edittext);
		weightEditText = (EditText)findViewById(R.id.view_profile_weight_edittext);
		heightEditText = (EditText)findViewById(R.id.view_profile_height_edittext);
		genderGroup = (RadioGroup)findViewById(R.id.view_profile_gender_radio_group);
		weightGroup = (RadioGroup)findViewById(R.id.weight_unit_radio_group);
		heightGroup = (RadioGroup)findViewById(R.id.height_unit_radio_group);
		physActSpinner = (Spinner)findViewById(R.id.view_profile_spinner);
		

		
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
               getApplicationContext(), R.array.phys_act, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        physActSpinner.setAdapter(adapter);
		
		
		if (ProfileManager.getInstance(getApplicationContext()).getProfileMode() == 
					ProfileManager.PROFILE_MODE_EDIT){
			nameEditText.setText(ProfileManager.getInstance(getApplicationContext()).getCurrentProfileName());
			switch (ProfileManager.getInstance(getApplicationContext()).getCurrentProfileGender()){
			case ProfileManager.MALE :
				genderGroup.check(R.id.view_profile_gender_radio_button_male);
				break;
			case ProfileManager.FEMALE :
				genderGroup.check(R.id.view_profile_gender_radio_button_female);
				break;
			}
			ageEditText.setText(String.valueOf(ProfileManager.getInstance(getApplicationContext()).getCurrentProfileAge()));
			weightEditText.setText(String.valueOf(ProfileManager.getInstance(getApplicationContext()).getCurrentProfileWeight()));
			heightEditText.setText(String.valueOf(ProfileManager.getInstance(getApplicationContext()).getCurrentProfileHeight()));
			physActSpinner.setSelection(ProfileManager.getInstance(getApplicationContext()).getCurrentProfilePhysAct());
		}else{
			SharedPreferences prefs = getPreferences(0);
			
			//get temporary name
			nameEditText.setText(prefs.getString(PREFS_PROFILE_NAME, ""));
			
			//get temporary gender
			switch (prefs.getInt(PREFS_PROFILE_GENDER, -1)){
			case ProfileManager.MALE :
				genderGroup.check(R.id.view_profile_gender_radio_button_male);
				break;
			case ProfileManager.FEMALE :
				genderGroup.check(R.id.view_profile_gender_radio_button_female);
				break;
			default:
				genderGroup.clearCheck();
				break;
			}
			
			//get temporary age
			ageEditText.setText(prefs.getString(PREFS_PROFILE_AGE, ""));
			
			//get temporary weight
			weightEditText.setText(prefs.getString(PREFS_PROFILE_WEIGHT, ""));
			switch (prefs.getInt(PREFS_WEIGHT_UNIT, METRIC)){
			case METRIC :
				weightGroup.check(R.id.weight_unit_radio_button_metric);
				break;
			case ENGLISH :
				weightGroup.check(R.id.weight_unit_radio_button_english);
				break;
			}
			
			//get temporary height			
			heightEditText.setText(prefs.getString(PREFS_PROFILE_HEIGHT, ""));
			switch (prefs.getInt(PREFS_HEIGHT_UNIT, METRIC)){
			case METRIC :
				heightGroup.check(R.id.height_unit_radio_button_metric);
				break;
			case ENGLISH :
				heightGroup.check(R.id.height_unit_radio_button_english);
				break;
			}
			
			//get temporary phys act
			physActSpinner.setSelection(prefs.getInt(PREFS_PROFILE_PHYSACT, 0));
		}
		
		
		
		saveButton.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v){
				//check name presence and spelling
				String name = nameEditText.getText().toString();
				if ( name.equals("") ){
					Toast.makeText(getApplicationContext(), R.string.view_profile_specify_name,
							Toast.LENGTH_SHORT).show();
					return;
				}
				if ( name.contains("\"") || name.contains("_") || name.contains("%") ){
					Toast.makeText(getApplicationContext(), R.string.view_profile_dont_use,
							Toast.LENGTH_LONG).show();
					return;
				}
				if ( ProfileManager.getInstance(getApplicationContext()).profileNameExists(name) && 
						(ProfileManager.getInstance(getApplicationContext()).getProfileMode() ==	ProfileManager.PROFILE_MODE_CREATE) ){
//					Log.v("ex","exists = "+name);
					Toast.makeText(getApplicationContext(), R.string.view_profile_profile_exists,
							Toast.LENGTH_LONG).show();
					return;
				}
				
				//check that gender is specified
				if (heightGroup.getCheckedRadioButtonId() == -1){
					Toast.makeText(getApplicationContext(), R.string.view_profile_specify_gender,
							Toast.LENGTH_SHORT).show();
					return;
				}
				
				//check that age is specified
				String age = ageEditText.getText().toString();
				if ( age.equals("") || Integer.parseInt(age) < 3){
					Toast.makeText(getApplicationContext(), R.string.view_profile_specify_age_message,
							Toast.LENGTH_SHORT).show();
					return;
				}
				
				//check that weight is specified
				String weight = weightEditText.getText().toString();
				if ( weight.equals("") ){
					Toast.makeText(getApplicationContext(), R.string.view_profile_specify_weight,
							Toast.LENGTH_SHORT).show();
					return;
				}
				
				//check that height is specified
				String height = heightEditText.getText().toString();
				if ( height.equals("") ){
					Toast.makeText(getApplicationContext(), R.string.view_profile_specify_height,
							Toast.LENGTH_SHORT).show();
					return;
				}
				
				//save name
				ProfileManager.getInstance(getApplicationContext()).setNewProfileName(nameEditText.getText());
				
				//save gender
				switch(genderGroup.getCheckedRadioButtonId()){
					case R.id.view_profile_gender_radio_button_male :
						ProfileManager.getInstance(getApplicationContext()).setNewProfileGender(ProfileManager.MALE);
						break;
					case R.id.view_profile_gender_radio_button_female :
						ProfileManager.getInstance(getApplicationContext()).setNewProfileGender(ProfileManager.FEMALE);
						break;
				}
				
				//save age
				ProfileManager.getInstance(getApplicationContext()).setNewProfileAge(Integer.parseInt(age));
				
				//save weight
				if (weightGroup.getCheckedRadioButtonId() == R.id.weight_unit_radio_button_metric)
					ProfileManager.getInstance(getApplicationContext()).setNewProfileWeight(Integer.parseInt(weight));
				else
					ProfileManager.getInstance(getApplicationContext()).setNewProfileWeight((int)Math.round( 
							Integer.parseInt(weight)*ProfileManager.LB_TO_KG ) );
				
				//save height
				if (heightGroup.getCheckedRadioButtonId() == R.id.height_unit_radio_button_metric)
					ProfileManager.getInstance(getApplicationContext()).setNewProfileHeight(Integer.parseInt(height));
				else
					ProfileManager.getInstance(getApplicationContext()).setNewProfileHeight((int)Math.round( 
							Integer.parseInt(height)*ProfileManager.IN_TO_CM ) );
				
				//save phys act
				ProfileManager.getInstance(getApplicationContext()).setNewProfilePhysActivity(physActSpinner.getSelectedItemPosition());
				
				
				ProfileManager.getInstance(getApplicationContext()).saveNewOrUpdateProfile();
				
				SharedPreferences.Editor editor = getPreferences(0).edit();
				editor.remove(PREFS_HEIGHT_UNIT);
				editor.remove(PREFS_PROFILE_AGE);
				editor.remove(PREFS_PROFILE_GENDER);
				editor.remove(PREFS_PROFILE_HEIGHT);
				editor.remove(PREFS_PROFILE_NAME);
				editor.remove(PREFS_PROFILE_PHYSACT);
				editor.remove(PREFS_PROFILE_WEIGHT);
				editor.remove(PREFS_WEIGHT_UNIT);
				editor.commit();
				
				
				Intent intent = new Intent();
				if (ProfileManager.getInstance(getApplicationContext()).getProfileMode() == ProfileManager.PROFILE_MODE_CREATE &&
						back == false){
					intent.setClass(getApplicationContext(), EatenTodayActivity.class);
					ProfileManager.getInstance(getApplicationContext()).setCurrentProfile(name);
				}else if( caller == CALLER_EATEN_TODAY )
        			intent.setClass(getApplicationContext(), EatenTodayActivity.class);
        		else
        			intent.setClass(getApplicationContext(), ProfileChooseActivity.class);
				intent.putExtra(ProfileChooseActivity.INTENT_EXTRA_NAME, 
						ProfileChooseActivity.CALLER_VIEW_PROFILE);
        		startActivity(intent);
        		finish();
			}
		});
		cancelButton.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v){
				if(	TextUtils.isEmpty(nameEditText.getText()) &&
					TextUtils.isEmpty(ageEditText.getText()) &&
					TextUtils.isEmpty(weightEditText.getText()) &&
					TextUtils.isEmpty(heightEditText.getText())		
					){
					Intent intent = new Intent();
	        		if(caller == CALLER_EATEN_TODAY)
	        			intent.setClass(getApplicationContext(), EatenTodayActivity.class);
	        		else
	        			intent.setClass(getApplicationContext(), ProfileChooseActivity.class);
	        		startActivity(intent);
	        		finish();
					return;
				}
				AlertDialog.Builder builder = new AlertDialog.Builder(ViewProfileActivity.this);
				if(ProfileManager.getInstance(getApplicationContext()).getProfileMode() == ProfileManager.PROFILE_MODE_EDIT)
					builder.setMessage(getString(R.string.profile_create_alert_message_edit));
				else
					builder.setMessage(getString(R.string.profile_create_alert_message_create));
				builder.setNegativeButton(R.string.profile_create_alert_dialog_negative_button_text, 
						new DialogInterface.OnClickListener(){
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							}
						});
				builder.setPositiveButton(R.string.profile_create_alert_dialog_positive_button_text, 
						new DialogInterface.OnClickListener(){
						@Override
						public void onClick(DialogInterface dialog,	int which) {
							SharedPreferences.Editor editor = getPreferences(0).edit();
							editor.remove(PREFS_HEIGHT_UNIT);
							editor.remove(PREFS_PROFILE_AGE);
							editor.remove(PREFS_PROFILE_GENDER);
							editor.remove(PREFS_PROFILE_HEIGHT);
							editor.remove(PREFS_PROFILE_NAME);
							editor.remove(PREFS_PROFILE_PHYSACT);
							editor.remove(PREFS_PROFILE_WEIGHT);
							editor.remove(PREFS_WEIGHT_UNIT);
							editor.commit();
							Intent intent = new Intent();
							if(caller == CALLER_EATEN_TODAY)
			        			intent.setClass(getApplicationContext(), EatenTodayActivity.class);
			        		else
			        			intent.setClass(getApplicationContext(), ProfileChooseActivity.class);
							
			        		startActivity(intent);
			        		finish();
						}
					});
				builder.show();				
			}
		});
		
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(	TextUtils.isEmpty(nameEditText.getText()) &&
					TextUtils.isEmpty(ageEditText.getText()) &&
					TextUtils.isEmpty(weightEditText.getText()) &&
					TextUtils.isEmpty(heightEditText.getText())	&&	
					ProfileManager.getInstance(getApplicationContext()).getProfileMode() == ProfileManager.PROFILE_MODE_CREATE){
					
					SharedPreferences.Editor editor = getPreferences(0).edit();
					editor.remove(PREFS_HEIGHT_UNIT);
					editor.remove(PREFS_PROFILE_AGE);
					editor.remove(PREFS_PROFILE_GENDER);
					editor.remove(PREFS_PROFILE_HEIGHT);
					editor.remove(PREFS_PROFILE_NAME);
					editor.remove(PREFS_PROFILE_PHYSACT);
					editor.remove(PREFS_PROFILE_WEIGHT);
					editor.remove(PREFS_WEIGHT_UNIT);
					editor.commit();
					
					Intent intent = new Intent();
	        		if(caller == CALLER_EATEN_TODAY)
	        			intent.setClass(getApplicationContext(), EatenTodayActivity.class);
	        		else
	        			intent.setClass(getApplicationContext(), ProfileChooseActivity.class);
	        		startActivity(intent);
	        		finish();
					return true;
			}
			back = true;
			SharedPreferences.Editor editor = getPreferences(0).edit();
			editor.remove(PREFS_HEIGHT_UNIT);
			editor.remove(PREFS_PROFILE_AGE);
			editor.remove(PREFS_PROFILE_GENDER);
			editor.remove(PREFS_PROFILE_HEIGHT);
			editor.remove(PREFS_PROFILE_NAME);
			editor.remove(PREFS_PROFILE_PHYSACT);
			editor.remove(PREFS_PROFILE_WEIGHT);
			editor.remove(PREFS_WEIGHT_UNIT);
			editor.commit();
			saveButton.performClick();
			return true;
		}
	    return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onPause(){
		super.onPause();
//		Log.v("Act","onPause");
		
		SharedPreferences.Editor editor = getPreferences(0).edit();
		
		//save temporary name
		editor.putString(PREFS_PROFILE_NAME, nameEditText.getText().toString());

		//save temporary gender
		switch(genderGroup.getCheckedRadioButtonId()){
			case R.id.view_profile_gender_radio_button_male :
				editor.putInt(PREFS_PROFILE_GENDER, ProfileManager.MALE);
				break;
			case R.id.view_profile_gender_radio_button_female :
				editor.putInt(PREFS_PROFILE_GENDER, ProfileManager.FEMALE);
				break;
		}
		
		//save temporary age
		editor.putString(PREFS_PROFILE_AGE, ageEditText.getText().toString());
		
		//save temporary weight
		editor.putString(PREFS_PROFILE_WEIGHT, weightEditText.getText().toString());
		
		//save temporary weight unit
		switch(weightGroup.getCheckedRadioButtonId()){
			case R.id.weight_unit_radio_button_metric :
				editor.putInt(PREFS_WEIGHT_UNIT, METRIC);
				break;
			case R.id.weight_unit_radio_button_english :
				editor.putInt(PREFS_WEIGHT_UNIT, ENGLISH);
				break;
		}
		
		//save temporary height
		editor.putString(PREFS_PROFILE_HEIGHT, heightEditText.getText().toString());
		
		//save temporary height unit
		switch(heightGroup.getCheckedRadioButtonId()){
			case R.id.height_unit_radio_button_metric :
				editor.putInt(PREFS_WEIGHT_UNIT, METRIC);
				break;
			case R.id.height_unit_radio_button_english :
				editor.putInt(PREFS_WEIGHT_UNIT, ENGLISH);
				break;
		}
		
		//save temporary phys act
		editor.putInt(PREFS_PROFILE_PHYSACT, physActSpinner.getSelectedItemPosition());
		editor.commit();
	}

//	@Override
//	public void onResume(){
//		SharedPreferences prefs = getPreferences(0);
//			
//			//get temporary name
//			nameEditText.setText(prefs.getString(PREFS_PROFILE_NAME, ""));
//			
//			//get temporary gender
//			switch (prefs.getInt(PREFS_PROFILE_GENDER, -1)){
//			case ProfileManager.MALE :
//				genderGroup.check(R.id.view_profile_gender_radio_button_male);
//				break;
//			case ProfileManager.FEMALE :
//				genderGroup.check(R.id.view_profile_gender_radio_button_female);
//				break;
//			default:
//				genderGroup.clearCheck();
//				break;
//			}
//			
//			//get temporary age
//			ageEditText.setText(prefs.getString(PREFS_PROFILE_AGE, ""));
//			
//			//get temporary weight
//			weightEditText.setText(prefs.getString(PREFS_PROFILE_WEIGHT, ""));
//			switch (prefs.getInt(PREFS_WEIGHT_UNIT, METRIC)){
//			case METRIC :
//				weightGroup.check(R.id.weight_unit_radio_button_metric);
//				break;
//			case ENGLISH :
//				weightGroup.check(R.id.weight_unit_radio_button_english);
//				break;
//			}
//			
//			//get temporary height			
//			heightEditText.setText(prefs.getString(PREFS_PROFILE_HEIGHT, ""));
//			switch (prefs.getInt(PREFS_HEIGHT_UNIT, METRIC)){
//			case METRIC :
//				heightGroup.check(R.id.height_unit_radio_button_metric);
//				break;
//			case ENGLISH :
//				heightGroup.check(R.id.height_unit_radio_button_english);
//				break;
//			}
//			
//			//get temporary phys act
//			physActSpinner.setSelection(prefs.getInt(PREFS_PROFILE_PHYSACT, 0));
//	}
//	public void onResume(){
//		super.onResume();
//		Log.v("Act","onResume");
//	}
//	public void onRestart(){
//		super.onRestart();
//		Log.v("Act","onRestart");
//	}
//	public void onStop(){
//		super.onStop();
//		Log.v("Act","onStop");
//	}
//	public void onDestroy(){
//		super.onDestroy();
//		Log.v("Act","onDestroy");
//	}
//	public void onStart(){
//		super.onStart();
//		Log.v("Act","onStart");
//	}
	
}